package org.jtb.mensawotd;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;

class Prefs {
	private Context context = null;
	private SharedPreferences prefs;

	Prefs(Context context) {
		this.context = context;
		this.prefs = PreferenceManager.getDefaultSharedPreferences(context);
	}

	String getString(String key, String def) {
		String s = prefs.getString(key, def);
		return s;
	}

	long getLong(String key, long def) {
		long l = Long.parseLong(prefs.getString(key, Long.toString(def)));
		return l;
	}

	void setString(String key, String val) {
		Editor e = prefs.edit();
		e.putString(key, val);
		e.commit();
	}

	void setLong(String key, long val) {
		Editor e = prefs.edit();
		e.putString(key, Long.toString(val));
		e.commit();
	}

	long getLastUpdate() {
		return getLong("lastUpdate", -1);
	}

	void setLastUpdate() {
		setLong("lastUpdate", System.currentTimeMillis());
	}

	List<HistoryItem> getHistory() {
		String s = getString("history", "[]");

		try {
			JSONArray ja = new JSONArray(s);
			List<HistoryItem> items = new ArrayList<HistoryItem>();
			for (int i = 0; i < ja.length(); i++) {
				JSONObject jo = ja.getJSONObject(i);
				String word = jo.getString("word");
				String url = jo.getString("url");
				long time = jo.getLong("time");
				HistoryItem item = new HistoryItem(word, url, time);
				items.add(item);
			}
			Collections.sort(items);
			return items;
		} catch (JSONException e) {
			// corrupt, should never happen
			setString("history", null);
			return Collections.emptyList();
		}
	}

	HistoryItem addHistory(String word, String url, long time) {
		List<HistoryItem> items = getHistory();
		HistoryItem item = new HistoryItem(word, url, time);
		int i = items.indexOf(item);
		if (i == -1) {
			items.add(item);
			setHistory(items);
		} else {
			item = items.get(i);
		}
		return item;
	}

	private void setHistory(List<HistoryItem> items) {
		JSONArray ja = new JSONArray();
		try {
			for (HistoryItem item : items) {
				JSONObject jo = item.toJSONObject();
				ja.put(jo);
			}
		} catch (JSONException je) {
			Log.e("mensawordwidget", "error setting history", je);
		}
		String h = ja.toString();
		setString("history", h);
	}

	public void clearHistory() {
		prefs.edit().remove("history").commit();
	}

	public int getVersion() {
		Integer v = prefs.getInt("version", -1);
		return v;
	}

	public void setVersion(int version) {
		prefs.edit().putInt("version", version).commit();
	}

	void setState(WidgetState state) {
		setString("state", state.toString());
	}

	WidgetState getState() {
		String s = getString("state", "LOADING");
		return WidgetState.valueOf(s);
	}
}
